package com.zh.tea.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.github.pagehelper.PageInfo;
import com.zh.tea.entity.Brand;
import com.zh.tea.entity.Tea;
import com.zh.tea.entity.Type;
import com.zh.tea.service.BrandService;
import com.zh.tea.service.NewsService;
import com.zh.tea.service.TeaService;
import com.zh.tea.service.TypeService;
import com.zh.tea.service.impl.BrandServiceImpl;
import com.zh.tea.service.impl.NewsServiceImpl;
import com.zh.tea.service.impl.TeaServiceImpl;
import com.zh.tea.service.impl.TypeServiceImpl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
 * Servlet implementation class TeaServlet
 */
@WebServlet("/TeaServlet")
public class TeaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TeaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out=response.getWriter();
		HttpSession session= request.getSession();
		
		//创建Tea的serivce对象
		TeaService teas=new TeaServiceImpl();
		String opt=request.getParameter("opt");
		System.out.println(opt);
		if("add".equals(opt)){
			Tea tea=new Tea();
			String  typeid=null;
			String  brandid=null;
			String  teano=null;
			String  name=null;
			String  price=null;
			String  stock=null;
			String  spec=null;
			String  packspec=null;
			String  licenseno=null;
			String  season=null;
			String tech=null;
			String proloc=null;
			String producedate=null;
			String bzq=null;
			String shortinfo=null;
			//tech text  producedate bzq pic1 shortinfo
			
			String pic1=null;
			String pic2=null;
			String pic3=null;
			
			
			String file1 = null;
			String fileName1 = null;
			String file2 = null;
			String fileName2 = null;
			String file3 = null;
			String fileName3 = null;
			boolean flag = true;// 文件是否上传成功
			Date time = new Date();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			//新建一个FileItrm的工厂类分析input标签
			FileItemFactory factory=new DiskFileItemFactory();
			//创建input框分析器
			ServletFileUpload fileUpload=new ServletFileUpload(factory);
			//分析request请求
			try {
				List<FileItem> list=fileUpload.parseRequest(request);
				for(FileItem item:list){
					if(item.isFormField()){//普通表单字段
						if("typeid".equals(item.getFieldName())){
							typeid=item.getString("utf-8");
						}else if("brandid".equals(item.getFieldName())){
							brandid=item.getString("utf-8");
						}else if("teano".equals(item.getFieldName())){
							teano=item.getString("utf-8");
						}else if("name".equals(item.getFieldName())){
							name=item.getString("utf-8");
						}else if("price".equals(item.getFieldName())){
							price=item.getString("utf-8");
						}else if("stock".equals(item.getFieldName())){
							stock=item.getString("utf-8");
						}else if("spec".equals(item.getFieldName())){
							spec=item.getString("utf-8");
						}else if("packspec".equals(item.getFieldName())){
							packspec=item.getString("utf-8");
						}else if("licenseno".equals(item.getFieldName())){
							licenseno=item.getString("utf-8");
						}else if("season".equals(item.getFieldName())){
							season=item.getString("utf-8");
						}else if("tech".equals(item.getFieldName())){
							tech=item.getString("utf-8");
						}else if("proloc".equals(item.getFieldName())){
							proloc=item.getString("utf-8");
						}else if("producedate".equals(item.getFieldName())){
							producedate=item.getString("utf-8");
						}else if("bzq".equals(item.getFieldName())){
							bzq=item.getString("utf-8");
						}else if("shortinfo".equals(item.getFieldName())){
							shortinfo=item.getString("utf-8");
						}
					}else {//文件表单字段
						String ext1=null;
						String ext2=null;
						String ext3=null;
						File upfile1=null;
						File upfile2=null;
						File upfile3=null;
						String[] exts = { "jpg", "png", "JEPG", "gif" };

						List es = Arrays.asList(exts);
						if("pic1".equals(item.getFieldName())){
							
								file1 = item.getName();
								if(!"".equals(file1) && file1!=null) {
								 ext1 = FilenameUtils.getExtension(file1);
								String realPath = request.getServletContext().getRealPath("/upload");// 项目真实路径
								fileName1 = FilenameUtils.getBaseName(file1) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file1);
								upfile1 = new File(realPath, fileName1);
								if (es.contains(ext1)) {
									item.write(upfile1);
									tea.setPic1("upload\\" + fileName1);
								} else {
									
									flag = false;
								}
							}
							
							
						}else if("pic2".equals(item.getFieldName())){
							
								file2 = item.getName();
								if(!"".equals(file2) && file2!=null) {
								 ext2 = FilenameUtils.getExtension(file2);
								String realPath = request.getServletContext().getRealPath("/upload");// 项目真实路径
								fileName2 = FilenameUtils.getBaseName(file2) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file2);
								upfile2 = new File(realPath, fileName2);
								
								if (es.contains(ext2)) {
									item.write(upfile2);
									tea.setPic2("upload\\" + fileName2);
								} else {
									
									flag = false;
								}
							}
							
						}else if("pic3".equals(item.getFieldName())){
							
								file3 = item.getName();
								if(!"".equals(file3) && file3!=null) {
								 ext3 = FilenameUtils.getExtension(file3);
								String realPath = request.getServletContext().getRealPath("/upload");// 项目真实路径
								fileName3 = FilenameUtils.getBaseName(file3) + System.currentTimeMillis() + "."
										+ FilenameUtils.getExtension(file3);
								 upfile3 = new File(realPath, fileName3);
								 if (es.contains(ext3)) {
										item.write(upfile3);
										tea.setPic3("upload\\" + fileName3);
									} else {
										
										flag = false;
									}
							}
							
						}
						
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (flag) {
				if(!"".equals(brandid)) {
					tea.setBrandid(Integer.parseInt(brandid));
				}
				if(!"".equals(bzq)) {
					tea.setBzq(Integer.parseInt(bzq));
				}
				tea.setLicenseno(licenseno);
				tea.setPackspec(packspec);
				if(!"".equals(price)) {
					tea.setPrice(Double.parseDouble(price));
				}
				try {
					if(!"".equals(producedate)) {
						tea.setProducedate(df.parse(producedate));
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(!"".equals(typeid)) {
					tea.setTypeid(Integer.parseInt(typeid));
				}
				
				tea.setTech(tech);
				tea.setTeano(teano);
				if(!"".equals(stock)) {
					tea.setStock(Integer.parseInt(stock));
				}
				tea.setSpec(spec);
				tea.setShortinfo(shortinfo);
				tea.setSeason(season);
				tea.setProloc(proloc);
				tea.setName(name);
				
				int i = teas.addTea(tea);
				if (i > 0) {
					out.print("<script>alert('添加成功！');location.href='/tea/admin/ShowGoods.jsp';</script>");
				}else {
					out.print("<script>alert('添加失败！');location.href='/tea/admin/GoodsInsert.jsp';</script>");
				}
			}else {
				out.print("<script>alert('不允许此文件类型上传！添加失败！');location.href='/tea/admin/GoodsInsert.jsp';</script>");
			}
		}else if("sel".equals(opt)){
			String pageNo=request.getParameter("pageno");
			//String pageSize=request.getParameter("pagesize");
			Integer pageno = pageNo==null?1:Integer.parseInt(pageNo);
			PageInfo<Tea> paget= teas.getTea(null, pageno, 12);
			
			session.setAttribute("tealist", paget.getList());
			response.sendRedirect("showtealists.jsp");
			
		}else if("toupd".equals(opt)){
			String teaid=request.getParameter("teaid");
			Tea tea=teas.getTeaById(Integer.parseInt(teaid));
			request.setAttribute("tea", tea);
			request.getRequestDispatcher("../admin/UpadateGoods.jsp").forward(request, response);
			
		}
		//显示所有茶商品
		else if("showAll".equals(opt)){
			//检测session中有没有品牌和种类的值，如果没有重新查询
			Object typelist=session.getAttribute("typelist");
			Object brandlist=session.getAttribute("brandlist");
			List<Type> listtype;
			List<Brand> listbrand;
			if(typelist==null){
				TypeService types=new TypeServiceImpl()	;
				listtype=types.selectAllType();
				session.setAttribute("typelist",listtype );
			}else{
				listtype=(List<Type>)typelist;
			}
			if(brandlist==null){
				BrandService brands=new BrandServiceImpl();
				listbrand=brands.selectAllType();
				session.setAttribute("brandlist", listbrand);
			}else{
				listbrand=(List<Brand>)brandlist;
			}
			int currentNumber = Integer.parseInt(request.getParameter("page")==null?"1":request.getParameter("page"));//页码
	        String currentPage = request.getParameter("limit") == null ? "1" : request.getParameter("limit");//大小
			
	        PageInfo<Tea> paget= teas.getTea(null, currentNumber, Integer.parseInt(currentPage));
	        	List tealist=new ArrayList<>();
	        	for(Tea tea:paget.getList()){
	        		Map<String,Object> map=new HashMap();
	        		//将tea的对象转换成map
	        		 Class clazz = tea.getClass();
	        		 System.out.println(clazz);
	        	     Field[] fields = clazz.getDeclaredFields();
	        	     for (Field field : clazz.getDeclaredFields()) {
	        	      field.setAccessible(true);
	        	      String fieldName = field.getName();
	        	      Object value;
					try {
						value = field.get(tea);
						map.put(fieldName, value);
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	        	       
	        	    	}
	        	    //替换Map中的类型id
	        	     
	        	  for(Type type:listtype){
	        		  
	        		  if(map.get("typeid")!=null){
	        		  if(((type.getId()).toString()).equals((map.get("typeid")).toString())){
	        			  map.put("typeid", type.getName());
	        			  System.out.println((type.getId()).toString()+"="+map.get("typeid"));
	        			  break;
	        		  }
	        		  }
	        	  }
	        	  for(Brand brand:listbrand){
	        		  if(map.get("brandid")!=null){
	        		  if((brand.getId()).toString().equals((map.get("brandid")).toString())){
	        			  map.put("brandid", brand.getName());
	        			  break;
	        		  }
	        		  }
	        	  }
	        	 tealist.add(map);
	        	}
	        
	        

				JSONObject jsonObject = new JSONObject();
		        jsonObject.put("code", 0);
		        jsonObject.put("msg", "");
		        jsonObject.put("count", paget.getTotal());
		        jsonObject.put("data", tealist);
			
				String json=jsonObject.toString();
				out.print(json);
				
				}
		//删除茶商品
		else if("delete".equals(opt)) {
					String teano =request.getParameter("teano");
					if(!"".equals(teano)) {
						NewsService newss=new NewsServiceImpl();
						newss.deleteNews(teano);
						Tea tea=new Tea();
						tea.setTeano(teano);
				        TeaService tess=new TeaServiceImpl();
				        int count= tess.delTea(tea);
				        if (count>0) {
							response.sendRedirect("/tea/admin/GoodsDel.jsp");
						} 
				    }
				}
		else if("sel1".equals(opt)) {
			String teano = request.getParameter("teano");
			Tea teaone = teas.selectOneTea(teano);
			System.out.println(teaone.getTeano());
			session.setAttribute("tea", teaone);
			out.print("<script>location.href='/tea/admin/UpdateGoods.jsp'</script>");
		}
		else if("update".equals(opt)) {
			System.out.println("dddd");
			Tea tea=new Tea();
			String id=request.getParameter("id");
			String typeid=request.getParameter("typeid");
			String  brandid=request.getParameter("brandid");
			String  teano=request.getParameter("teano");
			String  name=request.getParameter("name");
			String  price=request.getParameter("price");
			String  stock=request.getParameter("stock");
			String  spec=request.getParameter("spec");
			String  packspec=request.getParameter("packspec");
			String  licenseno=request.getParameter("licenseno");
			String  season=request.getParameter("season");
			String tech=request.getParameter("tech");
			String proloc=request.getParameter("proloc");
			String producedate=request.getParameter("producedate");
			String bzq=request.getParameter("bzq");
			String shortinfo=request.getParameter("shortinfo");
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			if(id!=null) {
				tea.setId(Integer.parseInt(id));
			}
				if(typeid!=null) {
					tea.setTypeid(Integer.parseInt(typeid));
				}
				System.out.println("z");
				if(brandid!=null) {
					tea.setBrandid(Integer.parseInt(brandid));
				}
				if(bzq!=null) {
					tea.setBzq(Integer.parseInt(bzq));
				}
				
				tea.setLicenseno(licenseno);
				tea.setPackspec(packspec);
				if(price!=null) {
					tea.setPrice(Double.parseDouble(price));
				}
				try {
					if(producedate!=null) {
						tea.setProducedate(df.parse(producedate));
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				tea.setTech(tech);
				tea.setTeano(teano);
				if(stock!=null) {
					tea.setStock(Integer.parseInt(stock));
				}
				tea.setSpec(spec);
				tea.setShortinfo(shortinfo);
				tea.setSeason(season);
				tea.setProloc(proloc);
				tea.setName(name);
				System.out.println("q");
				int i = teas.updTea(tea);
				System.out.println(i);
				if (i > 0) {
					out.print("<script>alert('修改成功！');location.href='/tea/admin/ShowGoods.jsp';</script>");
				}
			}else if("teadetial".equals(opt)){
				String teaid=request.getParameter("teaid");
				Tea tea=teas.getTeaById(Integer.parseInt(teaid));
				session.setAttribute("tea", tea);
				request.getRequestDispatcher("teashow.jsp").forward(request, response);
			}else if("suggest".equals(opt)){
				String getword=request.getParameter("keyword");
				//String keyword=getword;
				List<Tea> tealist=teas.selectTeaByOr(getword, 1, 100);
				List backword =new ArrayList();
				for(Tea tea:tealist){
					backword.add(tea.getName());
				}
				
				if(backword!=null){
					out.write((JSONArray.fromObject(backword)).toString());
				}else{
					out.write("");
				}
			}else if("selname".equals(opt)) {
				String teaname = request.getParameter("teaname");
				Tea teaone = teas.selectTeaname(teaname);
				session.setAttribute("tea", teaone);
				response.sendRedirect("teashow.jsp");
			}else if("selltea".equals(opt)){
				String word=request.getParameter("word");
				//String keyword=getword;
				List<Tea> tealist=teas.selectTeaByOr(word, 1, 9);
				request.setAttribute("tealist", tealist);
				request.getRequestDispatcher("showtealists.jsp").forward(request, response);
			}else if("selltype".equals("opt")){
				Tea tea =new Tea();
				String brandid=request.getParameter("brandid");
				String typeid=request.getParameter("typeid");
				String proloc=request.getParameter("proloc");
				if(brandid!=null){
					Integer bid=Integer.parseInt(brandid);
					tea.setBrandid(bid);
				}
				if(typeid!=null){
					Integer tid=Integer.parseInt(typeid);
					tea.setTypeid(tid);
				}
				if(proloc!=null){
					tea.setProloc(proloc);
				}
				PageInfo<Tea> paget=teas.selectTeaByAnd(tea, 1, 9) ;
				session.setAttribute("tealist", paget.getList());
				response.sendRedirect("showtealists.jsp");
				
			}
	}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
